import PureUnitMachines from '../components/unit-machines';
import { getFetchStatus, invalidateCache } from 'actions/util';
import * as RunnableUnitAction from 'actions/runnable-unit';
import * as React from 'react';
import * as ReactRedux from 'react-redux';
import _ from 'lodash';

const mapStateToProps = (state, ownProps) => {
  const { id: unitId, machineList } = ownProps.unit;
  const machineStatusList = state.machineStatusListByUnitId[unitId] || [];

  return {
    fetching: getFetchStatus(state, RunnableUnitAction.listMachineStatusByUnitId, unitId),
    machines: machineList.map(machine => {
      const status = machineStatusList.find(s => machine.id === s.machineId);
      if (status === undefined) {
        return machine;
      }
      return Object.assign({}, machine, { imageName: status.image, imageStatus: status.state });
    })
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  const { id: unitId, machineList } = ownProps.unit;

  const init = () => {
    // 分配了机器才有必要去获取机器状态
    if (!_.isEmpty(machineList)) {
      return dispatch(RunnableUnitAction.listMachineStatusByUnitId(unitId));
    }
    return Promise.resolve(true);
  };

  return {
    onInit: init,
    onRefreshMachineStatus: () => {
      invalidateCache(RunnableUnitAction.listMachineStatusByUnitId, unitId);
      init();
    }
  };
};

class UnitMachines extends React.Component {
  componentDidMount() {
    this.props.onInit();
  }

  render() {
    return <PureUnitMachines {...this.props}/>;
  }
}

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(UnitMachines);
